package com.wbao.dianniu.ui;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.alibaba.mobileim.fundamental.widget.refreshlist.PullToRefreshBase.Mode;
import com.alibaba.mobileim.fundamental.widget.refreshlist.PullToRefreshBase.OnRefreshListener;
import com.alibaba.mobileim.fundamental.widget.refreshlist.PullToRefreshListView;
import com.bigkoo.pickerview.OptionsPickerView;
import com.bigkoo.pickerview.listener.OnDismissListener;
import com.umeng.analytics.MobclickAgent;
import com.wbao.dianniu.adapter.JobListAdapter;
import com.wbao.dianniu.customView.PickerView;
import com.wbao.dianniu.data.ChildZone;
import com.wbao.dianniu.data.JobListData;
import com.wbao.dianniu.data.Zone;
import com.wbao.dianniu.listener.IJobListListener;
import com.wbao.dianniu.logical.Const;
import com.wbao.dianniu.logical.GlobalContext;
import com.wbao.dianniu.manager.JobListManager;
import com.wbao.dianniu.utils.JsonUtil;
import com.wbao.dianniu.utils.Notification;
import com.wbao.dianniu.utils.Utils;
import com.wbao.dianniu.R;


/**
 * 找人才
 *
 * @author yejianjun
 */
public class JobListActivity extends BaseActivity implements IJobListListener {
    private ArrayList<View> mViewArray = new ArrayList<View>();
    private JobListManager manager;
    private List<JobListData> mList = new ArrayList<JobListData>();
    private JobListAdapter adapter;
    private PullToRefreshListView pullListView;
    private ListView listView;
    private ImageView searchBtn;
    private EditText searchET;
    private TextView noDataTV;
    private String strPost = "";
    private String strAddress = "";
    private String strSalary = "";
    private String strExperience = "";
    private final int PAGE_COUNTS = 10;
    private int currentPage = 0;
    private ToggleButton area_toggle;
    private ToggleButton xinzi_toggle;
    private ToggleButton experience_toggle;
    /**
     * 省数据
     */
    private ArrayList<String> provinceList = new ArrayList<>();
    /**
     * 市数据
     */
    private ArrayList<ArrayList<String>> cityList = new ArrayList<>();
    private OptionsPickerView pvOptions;
    //弹出选择对话框
    private Dialog dialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentLayout(R.layout.activity_job_list, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        setTitleName(getString(R.string.hiring_hall));
        initView();
        initData();
    }

    private void initView() {
        area_toggle = findViewById(R.id.area_toggleBtn);
        xinzi_toggle = findViewById(R.id.xinzi_toggleBtn);
        experience_toggle = findViewById(R.id.experience_toggleBtn);

        searchET = findViewById(R.id.search_input_edittext01);
        noDataTV = findViewById(R.id.no_find_data);
        searchBtn = findViewById(R.id.search_imagebutton01);
        searchBtn.setOnClickListener(this);

        pullListView = findViewById(R.id.trail_listView);
        pullListView.setMode(Mode.PULL_UP_TO_REFRESH);
        pullListView.setOnRefreshListener(onRefreshListener);
        listView = pullListView.getRefreshableView();
        registerForContextMenu(listView);
        searchET.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    Utils.hideSoftInput(JobListActivity.this, searchET);
                    strPost = searchET.getText().toString().trim();
                    adapter.clear();
                    currentPage = 0;
                    requestData(currentPage * PAGE_COUNTS, PAGE_COUNTS, strPost, strAddress, strSalary, strExperience);
                    return true;
                }
                return false;
            }
        });
        searchET.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // TODO Auto-generated method stub

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
                // TODO Auto-generated method stub

            }

            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub
                strPost = searchET.getText().toString().trim();
            }
        });
        area_toggle.setOnClickListener(this);
        xinzi_toggle.setOnClickListener(this);
        experience_toggle.setOnClickListener(this);
    }


    private void initData() {
        manager = new JobListManager(this);
        manager.addJobListListener(this);
        adapter = new JobListAdapter(this);
        adapter.setData(mList);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(itemClickListener);
        requestData(currentPage, PAGE_COUNTS, null, null, null, null);

    }

    /**
     * @param page       页码
     * @param rows       每页多少条
     * @param post       搜索的职务名称
     * @param address    搜索的地址
     * @param salary     搜索的薪资
     * @param experience 搜索的工作经验
     */
    private void requestData(int page, int rows, String post, String address, String salary, String experience) {
        manager.jobList(GlobalContext.getAccountId(), page, rows, post, address, salary, experience);
    }

    private int getPositon(View tView) {
        for (int i = 0; i < mViewArray.size(); i++) {
            if (mViewArray.get(i) == tView) {
                return i;
            }
        }
        return -1;
    }

    @Override
    public void onBackPressed() {
        if (null != dialog && dialog.isShowing()) {
            dialog.dismiss();
        } else if (null != pvOptions && pvOptions.isShowing()) {
            pvOptions.dismiss();
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public void onJobListFailure(int errorCode, String errorMsg) {
        pullListView.onRefreshComplete(false, false);
        Notification.toast(this, errorMsg == null ? "" : errorMsg);
    }

    @Override
    public void onJobListSuccess(List<JobListData> list) {
        pullListView.onRefreshComplete(false, false);
        if (null != list) {
            if (0 != currentPage) {
                adapter.addData(list);
            } else {
                adapter.setData(list);
            }
            mList = adapter.getList();
            adapter.notifyDataSetChanged();
            if (mList.size() == 0) {
                noDataTV.setVisibility(View.VISIBLE);
            } else {
                noDataTV.setVisibility(View.GONE);
            }
        }
    }

    OnItemClickListener itemClickListener = new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                                long id) {
            // TODO Auto-generated method stub
            Intent intent = new Intent();
            intent.putExtra(Const.INTENT_JOB_ID, mList.get(position - 1).getId());
            intent.setClass(JobListActivity.this, JobDetailsActivity.class);
            startActivity(intent);
        }
    };

    OnRefreshListener onRefreshListener = new OnRefreshListener() {

        @Override
        public void onRefresh() {
            //  上拉刷新 加载请求数据
            pullUpRequest();
        }
    };

    // 上拉刷新数据请求
    private void pullUpRequest() {
        //没有搜索结果 或者数据为空 上拉没有效果
        ++currentPage;
        requestData(currentPage * PAGE_COUNTS, PAGE_COUNTS, strPost, strAddress, strSalary, strExperience);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.search_imagebutton01:
                Utils.hideSoftInput(JobListActivity.this, searchET);
                strPost = searchET.getText().toString().trim();
                adapter.clear();
                currentPage = 0;
                requestData(currentPage * PAGE_COUNTS, PAGE_COUNTS, strPost, strAddress, strSalary, strExperience);
                break;
            case R.id.area_toggleBtn:
                // 隐藏键盘
                Utils.hideSoftInput(JobListActivity.this, searchET);
                initAreaData();
                break;
            case R.id.xinzi_toggleBtn:
                // 隐藏键盘
                Utils.hideSoftInput(JobListActivity.this, searchET);

                View viewMoney = showRealase(R.layout.job_release_money);
                PickerView pickerMoney = viewMoney.findViewById(R.id.picker_money);
                List<String> datas = new ArrayList<String>();
                final String[] xinziStr = getResources().getStringArray(R.array.salary_choose_array);
                for (int i = 0; i < xinziStr.length; i++) {
                    datas.add(xinziStr[i]);
                }
                pickerMoney.setData(datas);
                if ("".equals(strSalary)) {
                    strSalary = xinziStr[0];
                }
                pickerMoney.setOnSelectListener(new PickerView.onSelectListener() {

                    @Override
                    public void onSelect(String text) {
                        // TODO Auto-generated method stub
                        strSalary = text;
                    }
                });
                Button confirmMoney = viewMoney.findViewById(R.id.job_money_confirm);
                confirmMoney.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        xinzi_toggle.setText(strSalary);
                        if (null != dialog && dialog.isShowing()) {
                            dialog.dismiss();
                            xinzi_toggle.setChecked(false);
                        }
                        if (strSalary.contains("不限")) {
                            strSalary = "";
                        }
                        currentPage = 0;
                        requestData(0, PAGE_COUNTS, strPost, strAddress, strSalary, strExperience);
                    }
                });
                break;
            case R.id.experience_toggleBtn:
                // 隐藏键盘
                Utils.hideSoftInput(JobListActivity.this, searchET);

                View viewYear = showRealase(R.layout.job_release_money);
                PickerView pickerYear = viewYear.findViewById(R.id.picker_money);
                List<String> datasYear = new ArrayList<String>();
                String[] experience = getResources().getStringArray(R.array.job_experience_selected);
                for (int i = 0; i < experience.length; i++) {
                    datasYear.add(experience[i]);
                }
                pickerYear.setData(datasYear);
                if ("".equals(strExperience)) {
                    strExperience = experience[0];
                }
                pickerYear.setOnSelectListener(new PickerView.onSelectListener() {

                    @Override
                    public void onSelect(String text) {
                        // TODO Auto-generated method stub
                        strExperience = text;
                    }
                });
                Button confirmYear = viewYear.findViewById(R.id.job_money_confirm);
                confirmYear.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        experience_toggle.setText(strExperience);
                        if (null != dialog && dialog.isShowing()) {
                            dialog.dismiss();
                            experience_toggle.setChecked(false);
                        }
                        if (strExperience.contains("不限")) {
                            strExperience = "";
                        }
                        currentPage = 0;
                        requestData(0, PAGE_COUNTS, strPost, strAddress, strSalary, strExperience);
                    }
                });
                break;
            default:
                break;
        }

    }

    private View showRealase(int layoutId) {
        dialog = new Dialog(this, R.style.custom_Dialog);
        try {
            Window win = dialog.getWindow();
            win.getDecorView().setPadding(0, 0, 0, 0);
            win.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM);
            WindowManager.LayoutParams lp = win.getAttributes();
            lp.width = WindowManager.LayoutParams.MATCH_PARENT;
            lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
            win.setAttributes(lp);
            win.setWindowAnimations(R.style.buttom_animation);
        } catch (Exception e) {
            e.printStackTrace();
        }
        View view = LayoutInflater.from(this).inflate(layoutId, null);
        dialog.setContentView(view);
        dialog.setCancelable(true);
        dialog.show();
        return view;
    }

    /**
     * 地区选择器
     */
    private void initAreaData() {
        //选项选择器
        pvOptions = new OptionsPickerView(this);
        InputStream input = getResources().openRawResource(R.raw.zone2);
        String jsonData = Utils.inputStream2String(input, "utf-8");
        List<Zone> zoneList = JsonUtil.toObjectList(jsonData, Zone.class);
        for (Iterator iterator = zoneList.iterator(); iterator.hasNext(); ) {
            Zone zone = (Zone) iterator.next();
            provinceList.add(zone.getName());
            LinkedList<ChildZone> linkList = zone.getChildrens();
            ArrayList<String> arrayList = new ArrayList<String>();
            for (int i = 0; i < linkList.size(); i++) {
                arrayList.add(linkList.get(i).getName());
            }
            cityList.add(arrayList);
        }

        pvOptions.setPicker(provinceList, cityList, true);
        pvOptions.setTitle(getResources().getString(R.string.city_selected));
        pvOptions.setCyclic(false);

        pvOptions.setSelectOptions(0, 0);
        pvOptions.setOnoptionsSelectListener(new OptionsPickerView.OnOptionsSelectListener() {

            @Override
            public void onOptionsSelect(int options1, int option2, int options3) {
                if (option2 >= cityList.get(options1).size()) { // 快速滑动时，最后一个超过界限，则显示最后一个
                    option2 = cityList.get(options1).size() - 1;
                }
                String cityStr = cityList.get(options1).get(option2); // 市
                String provinceStr = provinceList.get(options1);// 省
                if (cityStr.equals("全部")) {
                    strAddress = provinceStr;
                } else {
                    strAddress = provinceList.get(options1) + cityList.get(options1).get(option2);
                }
                area_toggle.setText(strAddress);
                if (strAddress.contains("全部")) {
                    strAddress = "";
                }
                currentPage = 0;
                requestData(0, PAGE_COUNTS, strPost, strAddress, strSalary, strExperience);

            }
        });
        pvOptions.setOnDismissListener(new OnDismissListener() {
            @Override
            public void onDismiss(Object o) {
                area_toggle.setChecked(false);
            }
        });
        pvOptions.show();
    }


    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != manager) {
            manager.removeJobListListener(this);
        }
        if (null != dialog && dialog.isShowing()) {
            dialog.dismiss();
        }
        if (null != pvOptions && pvOptions.isShowing()) {
            pvOptions.dismiss();
        }
    }


}
